from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
import json


class ChatConsumer(WebsocketConsumer):

    def connect(self):
        self.service_uid = self.scope["url_route"]["kwargs"]["service_uid"]
        self.chat_group_name = 'char_%s' % self.service_uid
        # print(self.chat_group_name)
        # 加入连接时候处理
        async_to_sync(self.channel_layer.group_add)(
            self.chat_group_name,
            self.channel_name
        )

        self.accept()

    # 关闭channel处理时
    def disconnect(self, code):
        async_to_sync(self.channel_layer.group_discard)(
            self.chat_group_name,
            self.channel_name
        )

    # 收到websocket消息
    def recevice(self, content):
        text_data = json.loads(content)
        # 将信息发送给room group -- 也就是交给message处理
        async_to_sync(self.channel_layer.group_send)(self.chat_group_name, {'type': 'chat_message', 'message': content})

    # 收到room group消息
    def chat_message(self, event):
        message = event['message']
        # 将消息发送给websocket
        self.send(message)
